<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    :destroyOnClose="true"
    :okButtonProps="{ props: { disabled: disableSubmit } }"
    :okText="disableSubmit ? '关闭' : '确定'"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="规则名称">
          <a-input v-decorator="['name', validatorRules.name]" placeholder="请输入规则名称" :disabled="disableSubmit" />
        </a-form-item>

        <a-form-item label="门类型">
          <a-select v-decorator="['type', validatorRules.type]" placeholder="请选择门类型" :disabled="disableSubmit">
            <a-select-option :value="0">推拉</a-select-option>
            <a-select-option :value="1">平开</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="是否必填">
          <a-select
            v-decorator="['isMust', validatorRules.isMust]"
            placeholder="请选择是否必填"
            :disabled="disableSubmit"
          >
            <a-select-option :value="0">否</a-select-option>
            <a-select-option :value="1">是</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="排序号">
          <a-input-number
            v-decorator="['sortNo', validatorRules.sortNo]"
            placeholder="请输入排序号"
            :min="0"
            :max="9999"
            style="width: 100%"
            :disabled="disableSubmit"
          />
        </a-form-item>

        <a-form-item label="备注">
          <a-textarea v-decorator="['remark']" placeholder="请输入备注" :rows="3" :disabled="disableSubmit" />
        </a-form-item>

        <a-form-item label="规则值" v-if="!disableSubmit || (ruleValues && ruleValues.length > 0)">
          <div class="rule-values-container">
            <div class="rule-values-header">
              <span>规则可选值列表</span>
              <a-button v-if="!disableSubmit" type="dashed" size="small" icon="plus" @click="addRuleValue">
                添加选项
              </a-button>
            </div>

            <div class="rule-values-list">
              <div v-for="(value, index) in ruleValues" :key="index" class="rule-value-item">
                <a-input v-model="ruleValues[index]" placeholder="请输入规则值" :disabled="disableSubmit" />
                <a-button
                  v-if="!disableSubmit"
                  type="danger"
                  size="small"
                  icon="delete"
                  @click="removeRuleValue(index)"
                  style="margin-left: 8px"
                >
                  删除
                </a-button>
              </div>

              <div v-if="ruleValues.length === 0" class="empty-values">
                <a-empty description="暂无规则值" />
              </div>
            </div>
          </div>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'

export default {
  name: 'InquiryRuleModal',
  components: {},
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      ruleValues: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        name: {
          rules: [
            { required: true, message: '请输入规则名称!' },
            { min: 1, max: 100, message: '规则名称长度在1到100个字符之间!' },
          ],
        },
        type: {
          rules: [{ required: true, message: '请选择门类型!' }],
        },
        isMust: {
          rules: [{ required: true, message: '请选择是否必填!' }],
        },
        sortNo: {
          rules: [
            { required: true, message: '请输入排序号!' },
            { type: 'number', min: 0, max: 9999, message: '排序号必须在0-9999之间!' },
          ],
        },
      },
      url: {
        add: '/oms/inquiry/rule/add',
        edit: '/oms/inquiry/rule/edit',
        queryById: '/oms/inquiry/rule/queryById',
      },
      disableSubmit: false,
    }
  },
  created() {},
  methods: {
    add() {
      this.edit({})
    },
    copy(record) {
      this.edit(record, true)
    },
    edit(record, isCopy = false) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.ruleValues = []
      this.visible = true
      this.disableSubmit = false

      if (record.id && !isCopy) {
        this.loadRuleDetail(record.id)
      } else if (isCopy) {
        // 复制模式，清空ID
        this.model.id = null
        if (record.id) {
          this.loadRuleDetail(record.id, true)
        }
      }

      this.$nextTick(() => {
        this.form.setFieldsValue({
          name: this.model.name,
          type: this.model.type,
          isMust: this.model.isMust !== undefined ? this.model.isMust : 1,
          sortNo: this.model.sortNo || 0,
          remark: this.model.remark,
        })
      })
    },
    detail(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.ruleValues = []
      this.visible = true
      this.disableSubmit = true

      if (record.id) {
        this.loadRuleDetail(record.id)
      }

      this.$nextTick(() => {
        this.form.setFieldsValue({
          name: this.model.name,
          type: this.model.type,
          isMust: this.model.isMust !== undefined ? this.model.isMust : 1,
          sortNo: this.model.sortNo,
          remark: this.model.remark,
        })
      })
    },
    loadRuleDetail(id, isCopy = false) {
      this.confirmLoading = true
      getAction(this.url.queryById, { id: id })
        .then((res) => {
          if (res.success) {
            this.model = res.result.rule || {}
            this.ruleValues = (res.result.values || []).map((item) => item.value)

            if (isCopy) {
              this.model.id = null
              this.model.name = this.model.name + '_副本'
            }

            this.$nextTick(() => {
              this.form.setFieldsValue({
                name: this.model.name,
                type: this.model.type,
                isMust: this.model.isMust !== undefined ? this.model.isMust : 1,
                sortNo: this.model.sortNo,
                remark: this.model.remark,
              })
            })
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    loadRuleValues(ruleId) {
      getAction(`/oms/inquiry/rule/values/${ruleId}`)
        .then((res) => {
          if (res.success && res.result) {
            this.ruleValues = res.result.map((item) => item.value)
          }
        })
        .catch((err) => {
          console.error('加载规则值失败:', err)
        })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      if (this.disableSubmit) {
        this.handleCancel()
        return
      }

      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }

          let formData = Object.assign(this.model, values)
          formData.values = this.ruleValues.filter((v) => v && v.trim())

          console.log('提交的表单数据', formData)
          httpAction(httpurl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.handleCancel()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    addRuleValue() {
      this.ruleValues.push('')
    },
    removeRuleValue(index) {
      this.ruleValues.splice(index, 1)
    },
  },
}
</script>

<style lang="less" scoped>
.rule-values-container {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 12px;

  .rule-values-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    font-weight: 500;
  }

  .rule-values-list {
    .rule-value-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .empty-values {
      text-align: center;
      padding: 20px 0;
    }
  }
}
</style>
